'''
Created on Nov 29, 2010

@author: dexen
'''

import os
import time
import random

from dexen import SlaveTask

import common
from my_ind import MyInd


def _write_phenotype(phenotype):
    phenotype_path = os.path.join(common.HOUDINI_BASE_FILE, "phenotype")
    if not os.path.exists(phenotype_path):
        os.mkdir(phenotype_path)
    bgeo_file = os.path.join(phenotype_path, "eval.bgeo")
    f = open(bgeo_file, "w")
    f.write(phenotype)
    f.close()
    
def sim_ep(filename, phenotype):
    _write_phenotype(phenotype)
    common.enableHouModule()
    import hou
    basefile = os.path.join(common.HOUDINI_BASE_FILE, filename)
    hou.hipFile.load(basefile)
    print "I am after loading basefile"
    hou.node("/obj/geo1/OUT").cook()
    print "I am after cooking"
    node = hou.node("/obj/geo1/OUT")
    prim = node.geometry().prims()[0]
    att = prim.attribValue("TotalEnergyTransfer [KWh]")
    return att 

def sim_area(filename, phenotype):
    _write_phenotype(phenotype)
    common.enableHouModule()
    import hou
    basefile = os.path.join(common.HOUDINI_BASE_FILE, filename)
    hou.hipFile.load(basefile)
    hou.node("/obj/geo1/OUT").cook()
    node = hou.node("/obj/geo1/OUT")
    prims = node.geometry().prims()
    area_list = []
    for prim in prims:
        area = prim.attribValue("area")
        area_list.append(area)
    total = sum(area_list)
    
    return total

def dummy_eval():
    return random.randint(1,100)

class EvalEnergyTask(SlaveTask):
    def __init__(self):
        pass
    
    def __execute__(self, master_state, inds):
        print "I am in EvalEnergy"
        for ind in inds:
            assert isinstance(ind, MyInd)
            ind.energy.value = sim_ep("eval_energy.hipnc", ind.phenotype)
            #ind.energy.value = dummy_eval()
            ind.archive_data("Energy.txt", ind.energy.value)
        return inds

class EvalAreaTask(SlaveTask):
    def __init__(self):
        pass
    
    def __execute__(self, master_state, inds):
        print "I am in EvalArea"
        for ind in inds:
            assert isinstance(ind, MyInd)
            ind.area.value = sim_area("eval_area.hipnc", ind.phenotype)
            #ind.daylight.value = dummy_eval()
            ind.archive_data("Area.txt", ind.area.value)
        return inds

 
    